package com.duofan.gmall.order.web;

import com.duofan.gmall.common.constant.CommonConstant;
import com.duofan.gmall.common.exception.NoStockException;
import com.duofan.gmall.order.service.OrderService;
import com.duofan.gmall.order.vo.OrderConfirmVo;
import com.duofan.gmall.order.vo.OrderSubmitRespVo;
import com.duofan.gmall.order.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("confirmData", confirmVo);
        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes ra) {
        String msg = "下单失败: ";
        // 创建订单
        try {
            OrderSubmitRespVo respVo =  orderService.submitOrder(orderSubmitVo);
            if(respVo.getCode() == 0) {
                model.addAttribute("orderSubmitRespVo", respVo);
                // 成功
                return "pay";
            } else {

                switch (respVo.getCode()) {
                    case 1:
                        msg += "订单信息过期,请再次提交!";
                        break;
                    case 3:
                        msg += "商品价格发生变化,请确认后再次提交!";
                }
            }
        } catch (NoStockException e) {
            msg += e.getMessage();
        }
        ra.addFlashAttribute("msg", msg);
        return CommonConstant.REDIRECT_ORDER + "/toTrade";
    }
}
